package api

import (
	"gitee.com/yangwencheng/vblog/apps/blog"
	"gitee.com/yangwencheng/vblog/common"
	"gitee.com/yangwencheng/vblog/logger"
	"github.com/gin-gonic/gin"
)

func (h *Handler) QueryBlog(ctx *gin.Context) {
	// 请求对象
	qbr := blog.NewQueryBlogRequest()

	if err := ctx.ShouldBindQuery(qbr); err != nil {
		common.SendFail(ctx, err)
		return
	}
	blogSet, err := h.srv.QueryBlog(ctx, qbr)

	if err != nil {
		common.SendFail(ctx, err)
		return
	}
	common.SendSuccess(ctx, common.NewResult(blogSet))
}

func (h *Handler) CreateBlog(ctx *gin.Context) {

	cbr := blog.NewCreateBlogRequest()
	ctx.ShouldBind(cbr)
	cbr.Author = ctx.GetString("user_name")
	blog, err := h.srv.CreateBlog(ctx, cbr)
	if err != nil {
		common.SendFail(ctx, err)
		return
	}
	logger.GetLogger().Info().Any("blog", blog).Msg("成功")
	common.SendSuccess(ctx, common.NewResult("ok"))

}

func (h *Handler) ShowBlog(ctx *gin.Context) {
	sbr := &blog.ShowBlogRequest{}
	ctx.BindUri(sbr)
	blog, err := h.srv.ShowBlog(ctx, sbr)

	if err != nil {
		common.SendFail(ctx, err)
		return
	}
	common.SendSuccess(ctx, common.NewResult(blog))
}

func (h *Handler) UpdateBlog(ctx *gin.Context) {
	cbr := blog.NewCreateBlogRequest()
	ctx.BindJSON(cbr)
	blog := blog.NewBlog()
	ctx.BindUri(blog)

	blog, err := h.srv.UpdateBlog(ctx, cbr, blog)
	if err != nil {
		common.SendFail(ctx, err)
		return
	}
	common.SendSuccess(ctx, common.NewResult(blog))
}

func (h *Handler) DeleteBlog(ctx *gin.Context) {
	dbr := &blog.DeleteBlogRequest{}
	ctx.BindUri(dbr)
	blog, err := h.srv.DeleteBlog(ctx, dbr)

	if err != nil {
		common.SendFail(ctx, err)
		return
	}
	common.SendSuccess(ctx, common.NewResult(blog))
}
